﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_ContractBusiness : BaseBusiness<PB_Contract>, IPB_ContractBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_ContractBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_ContractDTO>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_Contract, Base_Department, PB_ContractDTO>> select = (a, b) => new PB_ContractDTO
            {
                DepartmentName = b.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                       EF.Functions.Like(x.Code, keyword)
                      || EF.Functions.Like(x.Name, keyword));
            }
            /// 项目合同权限
           q= q.Where(m => _operator.Property.DeptIds.Contains(m.DeptId));
            return await q.GetPageResultAsync(new PageInput());
        }

        public async Task<PB_Contract> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataAddLog(UserLogType.合同管理, "Name", "合同管理")]
        [DataRepeatValidate(new string[] { "Code" }, new string[] { "合同编号" })]
        public async Task AddDataAsync(PB_Contract data)
        {
            await InsertAsync(data);
        }

        [DataAddLog(UserLogType.合同管理, "Name", "合同管理")]
        [DataRepeatValidate(new string[] { "Code" }, new string[] { "合同编号" })]
        public async Task UpdateDataAsync(PB_Contract data)
        {
            await UpdateAsync(data);
        }
        [DataAddLog(UserLogType.合同管理, "Name", "合同管理")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}